package de.tu_darmstadt.gdi1.battleship.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class BattleshipClient {


	 	Socket requestSocket;
	 	ObjectOutputStream out;
	  	ObjectInputStream in;
	  	String message;
	  	
	  	public BattleshipClient(){}
	  	
	 	public void init(InetAddress addr, int port)
	 	{
	 		try{
	 			//1. creating a socket to connect to the server
	 			requestSocket = new Socket(addr, port);
	 			System.out.println("Connected to " + addr.getHostName() + " in port " + port);
	 			//2. get Input and Output streams
	 			out = new ObjectOutputStream(requestSocket.getOutputStream());
	 			out.flush();
	 			in = new ObjectInputStream(requestSocket.getInputStream());
	 			
	 			
	 		}
	 		catch(UnknownHostException unknownHost){
	 			System.err.println("You are trying to connect to an unknown host!");
	 		}
	 		catch(IOException ioException){
	 			ioException.printStackTrace();
	 		}
	 	}
	 	
	 	public void close() {
	 		try{
 				in.close();
 				out.close();
 				requestSocket.close();
 			}
 			catch(IOException ioException){
 				ioException.printStackTrace();
 			}
	 	}
	 	
	 	public void sendObject(NetObject obj)
	 	{
	 		try{
	 			out.writeObject(obj);
	 			out.flush();
	 			System.out.println("client>" + obj);
	 		}
	 		catch(IOException ioException){
	 			ioException.printStackTrace();
	 		}
	 	}
	 	
	 	public NetObject receiveObject() {
	 		NetObject no = null;
 				try{
 					no = (NetObject)in.readObject();
 					System.out.println("server>" + no);
 				}
 				catch(ClassNotFoundException e){
 					System.err.println("data received in unknown format");
 				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
 				return no;
	 	}
	 	
	 	public static void main(String args[]) throws UnknownHostException, InterruptedException
	 	{
	 		BattleshipClient client = new BattleshipClient();
	 		client.init(InetAddress.getByName("192.168.13.49"),1337);
	 		NetObject no = new NetObject();
	 		no.setMessage("Hallo Alex");
	 		client.sendObject(no);
	 		client.close();
	 	}
	 }
	

